#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    ,myTimer(new QTimer(this)),myLabel(new QLabel(this))
{
    ui->setupUi(this);

#if mainWindowsDebug
     this->tmpd = new Database("..\\..\\learn_test1_database.db");
#endif

    this->setWindowTitle("主界面");

    connect(ui->btn_exit,SIGNAL(clicked()),this,SLOT(close()));//qt4的用法，由于SIGNAL中内容相当于读取字符串，编译器不会报错，所以现在不被推荐使用

    this->myTimer->start(1000);
    MainWindow::update_time_dispose();//先显示
    connect(this->myTimer,&QTimer::timeout,this,&MainWindow::update_time_dispose);

    QStatusBar* tmpStatusBar = this->statusBar();
    tmpStatusBar->addPermanentWidget(myLabel);
    // tmpStatusBar->setSizeGripEnabled(false);
    tmpStatusBar->showMessage("欢迎使用电脑配件库存管理系统",5000);

    MainWindow::loadPartsData();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::loadPartsData()
{
    QSqlDatabase tmpDB = QSqlDatabase::database();

    if(!tmpDB.isOpen())
    {
        QMessageBox::critical(this,"数据库打开提示","数据库打开失败");
        return;
    }

    qDebug() << QFileInfo(tmpDB.databaseName()).absoluteFilePath();

    this->sqlModel = new QSqlQueryModel(this);

    this->sqlModel->setQuery("SELECT * FROM PARTS",tmpDB);

    if(this->sqlModel->lastError().isValid())
    {
        QMessageBox::critical(this,"Query错误","无法执行Query语句" + this->sqlModel->lastError().text());
        return;
    }


    if(this->sqlModel->rowCount() == 0)
    {
        QMessageBox::information(this,"数据量提示","配件表中为空");
    }

    this->sqlModel->setHeaderData(0,Qt::Horizontal,tr("ID"));
    this->sqlModel->setHeaderData(1,Qt::Horizontal,tr("配件名字"));
    this->sqlModel->setHeaderData(2,Qt::Horizontal,tr("配件类型"));
    this->sqlModel->setHeaderData(3,Qt::Horizontal,tr("价格"));
    this->sqlModel->setHeaderData(4,Qt::Horizontal,tr("数量"));

    ui->tableView->setModel(this->sqlModel);

    ui->tableView->setAlternatingRowColors(true);
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableView->verticalHeader()->hide();
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);

    ui->tableView->setSortingEnabled(true);
}

void MainWindow::update_time_dispose()
{
    QTime tmpTime = QTime::currentTime();
    QString tmpString = tmpTime.toString("hh:mm:ss");
    myLabel->setText(tmpString);
}

void MainWindow::refresh_table()
{
    this->sqlModel->setQuery("SELECT * FROM PARTS");
    if(this->sqlModel->lastError().isValid())
    {
        QMessageBox::information(this,"刷新表格提示","刷新表格执行语句失败:"+this->sqlModel->lastError().text());
        return;
    }
    ui->tableView->setModel(this->sqlModel);
}


void MainWindow::on_btn_add_clicked()
{
    QString name = ui->le_part_name->text();
    QString type = ui->le_part_type->text();
    double price = ui->le_part_price->text().toDouble();
    int num = ui->le_part_num->text().toInt();

    QSqlQuery query("INSERT INTO PARTS (name,type,price,num) VALUES (?,?,?,?)");
    query.addBindValue(name);
    query.addBindValue(type);
    query.addBindValue(price);
    query.addBindValue(num);

    if(!query.exec())
    {
        QMessageBox::information(this,"插入数据提示","插入数据失败:"+ query.lastError().text());
        return;
    }
    MainWindow::refresh_table();
}


void MainWindow::on_btn_del_clicked()
{
    QModelIndexList selectRows = ui->tableView->selectionModel()->selectedRows();//获取表格的选择模型 获取所有被选中行的索引列表
    if(selectRows.isEmpty())
    {
        QMessageBox::information(this,"删除数据提示","请先选中一条数据之后再删除");
        return;
    }

    int id = this->sqlModel->data(this->sqlModel->index(selectRows[0].row(), 0)).toInt();//sql模型->数据( 模型->索引(选中的第一条的行号,0列) ) //sql模型->data(sql模型->index(行,列))

    if(QMessageBox::question(this,"删除数据提示","是否确认删除这条数据",QMessageBox::Ok | QMessageBox::No) ==QMessageBox::No)
        return;

    QSqlQuery query("DELETE FROM PARTS WHERE ID = ?");
    query.addBindValue(id);

    if(!query.exec())
    {
        QMessageBox::information(this,"删除数据提示","删除数据执行语句失败:"+query.lastError().text());
        return;
    }

    MainWindow::refresh_table();
}


void MainWindow::on_btn_update_clicked()
{
    QModelIndexList selectRows  = ui->tableView->selectionModel()->selectedRows();

    if(selectRows.empty())
    {
        QMessageBox::information(this,"修改数据提示","请先选中一条数据之后再点击修改按钮");
        return;
    }

    int id = this->sqlModel->data(this->sqlModel->index(selectRows[0].row(),0)).toInt();

    QSqlQuery query("UPDATE PARTS SET name = ?, type = ?, price = ?, num = ? WHERE id = ?");//UPDATE → SET → WHERE
    query.addBindValue(ui->le_part_name->text());
    query.addBindValue(ui->le_part_type->text());
    query.addBindValue(ui->le_part_price->text().toDouble());
    query.addBindValue(ui->le_part_num->text().toInt());
    query.addBindValue(id);

    if(!query.exec())
    {
        QMessageBox::information(this,"修改数据提示","执行修改数据语句失败:"+query.lastError().text());
        return;
    }
    MainWindow::refresh_table();
}


void MainWindow::on_btn_find_clicked()
{
    QString condition = ui->le_find_part_name_or_type->text();//条件

    if(condition.isEmpty())
        MainWindow::refresh_table();

    QString query =
        "SELECT * FROM PARTS WHERE name LIKE '%" + condition + "%' OR type LIKE '%" +condition +"%'";
    this->sqlModel->setQuery(query);

    if(this->sqlModel->lastError().isValid())
    {
        QMessageBox::information(this,"查找信息提示","查找信息语句执行失败:"+this->sqlModel->lastError().text());
        return;
    }
    ui->tableView->setModel(this->sqlModel);
}


void MainWindow::on_tableView_clicked(const QModelIndex &index)
{
    ui->le_part_name->setText(this->sqlModel->data(this->sqlModel->index(index.row(),1)).toString());
    ui->le_part_type->setText(this->sqlModel->data(this->sqlModel->index(index.row(),2)).toString());
    ui->le_part_price->setText(this->sqlModel->data(this->sqlModel->index(index.row(),3)).toString());
    ui->le_part_num->setText(this->sqlModel->data(this->sqlModel->index(index.row(),4)).toString());
}
